package com.xtaller.easy.admin.controller.base;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.bean.AuthInfo;
import com.xtaller.common.bean.CacheInfo;
import com.xtaller.common.bean.JWTResult;
import com.xtaller.common.convert.J;
import com.xtaller.common.convert.S;
import com.xtaller.common.convert.V;
import com.xtaller.common.convert.W;
import com.xtaller.common.kit.JwtKit;
import com.xtaller.common.kit.MD5Kit;
import com.xtaller.easy.admin.base.TApi;
import com.xtaller.easy.admin.config.R;
import com.xtaller.easy.admin.model.BaseUser;
import com.xtaller.easy.admin.service.impl.BaseUserService;
import com.xtaller.easy.admin.specification.MyPassword;
import com.xtaller.easy.admin.specification.RoleSet;
import com.xtaller.easy.admin.specification.UserCreate;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by Taller on 2018/5/8
 */
@Api(tags = "用户管理api")
@RestController
@RequestMapping("/v1/base")
@CrossOrigin   //跨域服务注解
public class UserApi extends TApi {
    @Autowired
    private BaseUserService userService;

    private Map<String,String> BaseVerify(){
        Map<String,String> verify = new HashMap<>();
        verify.put("loginName","登录名称不能为空");
        verify.put("password","登录密码不能为空");
        return verify;
    }

    @GetMapping("/user/{index}-{size}-{key}")
    @ApiOperation(value = "获取用户列表")
    public Object getUserList(@ApiParam("当前页码") @PathVariable("index") int index,
                              @ApiParam("每页显示条数") @PathVariable("size") int size,
                              @ApiParam("关键字查询") @PathVariable("key") String query){
        String where = "";
        if(query.trim().length() > 0){
            where = o2q(query);
        }
        return R.ok(userService.getPageList(index, size, where));
    }

    @PostMapping("/user")
    @ApiOperation(value = "创建用户")
    public Object createUser(@RequestBody UserCreate object){
        JSONObject check = V.checkEmpty(BaseVerify(), object);
        if(check.getBoolean("check"))
            return R.error(check.getString("message"));
        if(userService.exist(W.f(W.and("loginName", "eq", object.getLoginName()))))
            return R.error("登录名已经存在请更换");
        String salt = S.random(6);
        String password = MD5Kit.encode(String.format("%s%s", object.getPassword(), salt));
        BaseUser user = new BaseUser();
        user.setLoginName(object.getLoginName());
        user.setSalt(salt);
        user.setPassword(password);
        user = userService.createBaseUser(user);
        if(user == null)
            return R.error("创建用户失败");
        JSONObject result = J.o2j(user);


        result.put("label", userService.getUserLabel(user.getId(), new ArrayList<>()));
        result.put("role", new ArrayList<>());
        return R.ok("创建成功", result);
    }

    @PutMapping("/user/role")
    @ApiOperation(value = "分配角色")
    public Object setRole(@RequestBody RoleSet object){
        if(userService.configUserRoel(object))
            return R.ok("角色分配成功");
        return R.error("角色分配失败");
    }

    @PutMapping("/user/password/{id}")
    @ApiOperation(value = "重置密码")
    public Object initPwd(@PathVariable("id") String id){
        if(userService.selectById(id) == null)
            return R.error("数据Id异常");
        BaseUser user = new BaseUser();
        String salt = S.random(6);
        String tem = S.random(8);
        String pwd = MD5Kit.encode(String.format("%s%s", tem, salt));
        user.setId(id);
        user.setPassword(pwd);
        user.setSalt(salt);
        if(userService.updateBaseUser(user) != null)
            return R.ok("重置密码成功,请牢记红色字符【 <span style='color:red;'>"+tem+"</span> 】");
        return R.error("重置密码失败");
    }

    @PutMapping("/user/my-password")
    @ApiOperation(value = "修改自己的密码")
    public Object myPassword(@RequestBody MyPassword object){
        String userId = getUserIdByToken();
        BaseUser user = userService.selectById(userId);
        // 验证旧密码
        String oldPwd = user.getPassword();
        String inputPwd = MD5Kit.encode(S.apppend(object.getOldPwd(), user.getSalt()));
        // 密码比较
        if(!V.isEqual(inputPwd, oldPwd))
            return R.error("旧密码有误");

        String salt = S.random(6);
        String pwd = MD5Kit.encode(String.format("%s%s", object.getNewPwd(), salt));
        user.setPassword(pwd);
        user.setSalt(salt);
        if(userService.updateBaseUser(user) != null)
            return R.ok("密码修改成功,请重新登录");
        return R.error("密码修改失败");
    }

    @GetMapping("/user/login-out")
    @ApiOperation(value = "退出登录")
    public Object loginOut(){
        JWTResult jwt = JwtKit.validateJWT(getToken());
        Claims claims = jwt.getClaims();
        String userId = claims.getId();
        if(userService.selectById(userId) == null)
            return R.error(HttpStatus.FORBIDDEN,"token数据id异常", 1);

        AuthInfo auth = J.s2m(claims.getSubject(), AuthInfo.class);
        // 缓存检查/缓存数据
        CacheInfo info = cacheKit.getCacheInfo(userId);
        info.setJwt(auth.getPlatform(), "");
        // redis 缓存info数据
        cacheKit.setVal(userId, info);

        return R.ok("退出登录成功");
    }

    @DeleteMapping("/user/{id}")
    @ApiOperation(value = "删除用户")
    public Object deleteUser(@PathVariable("id") String id){
        if(userService.selectById(id) == null)
            return R.error("数据Id异常");
        if(userService.deleteBaseUser(id, getUserIdByToken()))
            return R.ok("删除成功");
        return R.error("删除失败请稍后再试");
    }

    @PutMapping("/user/status/{id}")
    @ApiOperation(value = "设置用户状态")
    public Object setStatus(@PathVariable("id") String id){
        BaseUser user = userService.selectById(id);
        if(user == null)
            return R.error("数据Id异常");
        int status = user.getStatus();
        status = status == 1 ? 0 : 1;
        user.setStatus(status);
        if(userService.updateBaseUser(user) != null)
            return R.ok("用户状态修改成功");
        return R.error("用户状态修改失败");
    }
}
